<template>
  <div class="donor-detail">
    <el-page-header @back="$router.back()" title="Back">
      <template #content>
        <span class="page-title">Donor Details</span>
      </template>
    </el-page-header>

    <div v-loading="loading" style="margin-top: 20px;">
      <!-- Basic Information -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>Basic Information</span>
            <el-button type="primary" @click="handleEdit">Edit</el-button>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="Donor ID">{{ donorInfo.donor_id }}</el-descriptions-item>
          <el-descriptions-item label="Code">{{ donorInfo.donor_code }}</el-descriptions-item>
          <el-descriptions-item label="Full Name">{{ donorInfo.full_name }}</el-descriptions-item>
          <el-descriptions-item label="Date of Birth">{{ donorInfo.date_of_birth }}</el-descriptions-item>
          <el-descriptions-item label="Blood Type">{{ donorInfo.blood_type }}</el-descriptions-item>
          <el-descriptions-item label="Height">{{ donorInfo.height_cm }} cm</el-descriptions-item>
          <el-descriptions-item label="Weight">{{ donorInfo.weight_kg }} kg</el-descriptions-item>
          <el-descriptions-item label="Education">{{ donorInfo.education_level }}</el-descriptions-item>
          <el-descriptions-item label="Occupation">{{ donorInfo.occupation }}</el-descriptions-item>
          <el-descriptions-item label="Email">{{ donorInfo.contact_email }}</el-descriptions-item>
          <el-descriptions-item label="Phone">{{ donorInfo.contact_phone }}</el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="donorInfo.is_active ? 'success' : 'info'">
              {{ donorInfo.is_active ? 'Active' : 'Inactive' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- Statistics -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <el-card>
            <el-statistic title="Vial Count" :value="statistics.vialCount" />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <el-statistic title="Order Count" :value="statistics.orderCount" />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <el-statistic title="Offspring Count" :value="statistics.offspringCount" />
          </el-card>
        </el-col>
      </el-row>

      <!-- Medical Screening Records -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>Medical Screening Records</span>
            <el-tag v-if="screeningCompleteness.total > 0" 
                    :type="screeningCompleteness.completed === screeningCompleteness.total ? 'success' : 'warning'">
              {{ screeningCompleteness.completed }}/{{ screeningCompleteness.total }} Completed
            </el-tag>
          </div>
        </template>
        
        <div class="screening-checklist">
          <!-- Infectious Disease Screening -->
          <div class="screening-category">
            <h4 class="category-title">Infectious Disease Screening</h4>
            <el-row :gutter="16">
              <el-col :span="12" v-for="test in ['HIV', 'Hepatitis B', 'Hepatitis C', 'Syphilis']" :key="test">
                <div class="screening-item" :class="getScreeningClass(test)">
                  <div class="item-header">
                    <span class="item-name">{{ getTestDisplayName(test) }}</span>
                    <el-tag :type="getScreeningTagType(test)" size="small">
                      {{ getScreeningStatus(test) }}
                    </el-tag>
                  </div>
                  <div class="item-details" v-if="getScreeningRecord(test)">
                    <div class="detail-row">
                      <span class="label">Test Date:</span>
                      <span>{{ formatDate(getScreeningRecord(test).screening_date) }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="label">Result:</span>
                      <el-tag :type="getResultType(getScreeningRecord(test).result)" size="small">
                        {{ getScreeningRecord(test).result }}
                      </el-tag>
                    </div>
                    <div class="detail-row">
                      <span class="label">Lab:</span>
                      <span>{{ getScreeningRecord(test).lab_name }}</span>
                    </div>
                    <div class="detail-row" v-if="getScreeningRecord(test).notes">
                      <span class="label">Notes:</span>
                      <span>{{ getScreeningRecord(test).notes }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- Genetic Screening -->
          <div class="screening-category">
            <h4 class="category-title">Genetic Screening</h4>
            <el-row :gutter="16">
              <el-col :span="12" v-for="test in ['Genetic Screening', 'Chromosome Analysis']" :key="test">
                <div class="screening-item" :class="getScreeningClass(test)">
                  <div class="item-header">
                    <span class="item-name">{{ getTestDisplayName(test) }}</span>
                    <el-tag :type="getScreeningTagType(test)" size="small">
                      {{ getScreeningStatus(test) }}
                    </el-tag>
                  </div>
                  <div class="item-details" v-if="getScreeningRecord(test)">
                    <div class="detail-row">
                      <span class="label">Test Date:</span>
                      <span>{{ formatDate(getScreeningRecord(test).screening_date) }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="label">Result:</span>
                      <el-tag :type="getResultType(getScreeningRecord(test).result)" size="small">
                        {{ getScreeningRecord(test).result }}
                      </el-tag>
                    </div>
                    <div class="detail-row">
                      <span class="label">Lab:</span>
                      <span>{{ getScreeningRecord(test).lab_name }}</span>
                    </div>
                    <div class="detail-row" v-if="getScreeningRecord(test).notes">
                      <span class="label">Notes:</span>
                      <span>{{ getScreeningRecord(test).notes }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- Semen Quality Testing -->
          <div class="screening-category">
            <h4 class="category-title">Semen Quality Testing</h4>
            <el-row :gutter="16">
              <el-col :span="12" v-for="test in ['Semen Analysis']" :key="test">
                <div class="screening-item" :class="getScreeningClass(test)">
                  <div class="item-header">
                    <span class="item-name">{{ getTestDisplayName(test) }}</span>
                    <el-tag :type="getScreeningTagType(test)" size="small">
                      {{ getScreeningStatus(test) }}
                    </el-tag>
                  </div>
                  <div class="item-details" v-if="getScreeningRecord(test)">
                    <div class="detail-row">
                      <span class="label">Test Date:</span>
                      <span>{{ formatDate(getScreeningRecord(test).screening_date) }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="label">Result:</span>
                      <el-tag :type="getResultType(getScreeningRecord(test).result)" size="small">
                        {{ getScreeningRecord(test).result }}
                      </el-tag>
                    </div>
                    <div class="detail-row">
                      <span class="label">Lab:</span>
                      <span>{{ getScreeningRecord(test).lab_name }}</span>
                    </div>
                    <div class="detail-row" v-if="getScreeningRecord(test).notes">
                      <span class="label">Notes:</span>
                      <span>{{ getScreeningRecord(test).notes }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>

      <!-- Vial List -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <span>Vial List</span>
        </template>
        <el-table :data="vialList" style="width: 100%">
          <el-table-column prop="vial_id" label="Vial ID" width="100" />
          <el-table-column prop="collection_date" label="Collection Date" />
          <el-table-column prop="motility_percent" label="Motility (%)" />
          <el-table-column prop="sperm_count_mil" label="Count (M/ml)" />
          <el-table-column prop="status" label="Status">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="storage_location" label="Storage Location" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { donorAPI } from '@/api'

const route = useRoute()
const router = useRouter()

const donorId = route.params.id
const loading = ref(false)
const donorInfo = ref({})
const vialList = ref([])
const screeningList = ref([])
const statistics = reactive({
  vialCount: 0,
  orderCount: 0,
  offspringCount: 0
})

// Standard screening checklist
const standardTests = [
  'HIV', 'Hepatitis B', 'Hepatitis C', 'Syphilis',
  'Genetic Screening', 'Chromosome Analysis', 'Semen Analysis'
]

// Screening completeness statistics
const screeningCompleteness = reactive({
  completed: 0,
  total: 7
})

onMounted(async () => {
  await loadDonorInfo()
})

const loadDonorInfo = async () => {
  loading.value = true
  try {
    // Get donor details
    const detailRes = await donorAPI.getDetail(donorId)
    donorInfo.value = detailRes.data || {}
    
    // Get vial list
    const vialsRes = await donorAPI.getVials(donorId)
    vialList.value = vialsRes.data || []
    statistics.vialCount = vialList.value.length
    
    // Get medical screening records
    const screeningsRes = await donorAPI.getScreenings(donorId)
    screeningList.value = screeningsRes.data || []
    
    // Calculate screening completeness
    screeningCompleteness.completed = standardTests.filter(test => 
      screeningList.value.some(s => s.test_name === test)
    ).length
    
    // Get offspring count
    const offspringRes = await donorAPI.getOffspringCount(donorId)
    statistics.offspringCount = offspringRes.data?.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  router.push(`/donors?edit=${donorId}`)
}

const getStatusType = (status) => {
  const typeMap = {
    'Available': 'success',
    'Reserved': 'warning',
    'Used': 'info',
    'Discarded': 'danger'
  }
  return typeMap[status] || 'info'
}

const getResultType = (result) => {
  if (!result) return 'info'
  const resultLower = result.toLowerCase()
  if (resultLower.includes('negative') || resultLower.includes('normal') || resultLower.includes('pass')) {
    return 'success'
  } else if (resultLower.includes('positive') || resultLower.includes('abnormal') || resultLower.includes('fail')) {
    return 'danger'
  }
  return 'info'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

// Get screening record for a test
const getScreeningRecord = (testName) => {
  return screeningList.value.find(s => s.test_name === testName)
}

// Get screening status
const getScreeningStatus = (testName) => {
  return getScreeningRecord(testName) ? 'Completed' : 'Pending'
}

// Get screening tag type
const getScreeningTagType = (testName) => {
  return getScreeningRecord(testName) ? 'success' : 'info'
}

// Get screening item CSS class
const getScreeningClass = (testName) => {
  return getScreeningRecord(testName) ? 'completed' : 'pending'
}

// Get test display name
const getTestDisplayName = (testName) => {
  const nameMap = {
    'HIV': 'HIV (Human Immunodeficiency Virus)',
    'Hepatitis B': 'Hepatitis B',
    'Hepatitis C': 'Hepatitis C',
    'Syphilis': 'Syphilis',
    'Genetic Screening': 'Genetic Screening',
    'Chromosome Analysis': 'Chromosome Analysis',
    'Semen Analysis': 'Semen Analysis'
  }
  return nameMap[testName] || testName
}
</script>

<style scoped>
.donor-detail {
  padding: 0;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.screening-checklist {
  padding: 10px 0;
}

.screening-category {
  margin-bottom: 30px;
}

.screening-category:last-child {
  margin-bottom: 0;
}

.category-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 15px 0;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.screening-item {
  border: 2px solid #EBEEF5;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 16px;
  transition: all 0.3s;
  background-color: #fafafa;
}

.screening-item.completed {
  border-color: #67C23A;
  background-color: #f0f9ff;
}

.screening-item.pending {
  border-color: #E4E7ED;
  background-color: #fafafa;
}

.screening-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.item-details {
  padding-top: 12px;
  border-top: 1px dashed #DCDFE6;
}

.detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.6;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  color: #606266;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-row span:not(.label) {
  color: #303133;
  flex: 1;
}
</style>

